#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    reply = Q_NULLPTR;
    //初始化
        m_accessManager = new QNetworkAccessManager();

}

Widget::~Widget()
{
    delete ui;
}

//接收函数
void Widget:: finished()
{
    QByteArray bytes=reply->readAll();

    QString str(bytes);
    qDebug()<<"str数据》》》"<<str;
    ui->textBrowser_2->setPlainText(str);
   const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
     if (reply->error() == QNetworkReply::NoError)
    {

     qDebug()<<"error问题》》"<<str;

     }
     else
       {

        // QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

         //statusCodeV是HTTP服务器的相应码，reply->error()是Qt定义的错误码，可以参考QT的文档
         qDebug( "found error ....错误code:  %d\n", (int)reply->error());
         qDebug(qPrintable(reply->errorString()));
       }
     reply = Q_NULLPTR;
        if (!redirectionTarget.isNull())
        {//如果网址跳转重新请求
        const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl());
        qDebug()<<"现在》》redirectedUrl:"<<redirectedUrl.url();
        qDebug()<<"真实地址:%1"<<redirectedUrl.url();
        Post(redirectedUrl);
        return;
        }

        html_text = bytes;
        qDebug()<<"get ready,read size:"<<html_text.size();
     reply->deleteLater();
}

void Widget::on_pushButton_clicked()
{
   QString uus="https://u.y.qq.com/cgi-bin/musics.fcg?";
    html_text = "";
   // Post(QUrl(ui->lineEdit->text()));
     Post(QUrl(uus));

}
void Widget::Post(QUrl u)
{
     url=u;
    QNetworkRequest request;
        QSslConfiguration conf = request.sslConfiguration();
        conf.setPeerVerifyMode(QSslSocket::VerifyNone);
        conf.setProtocol(QSsl::TlsV1SslV3);
        request.setSslConfiguration(conf);
        request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json")); //设置数据类型

        request.setUrl(QUrl(url));

        QJsonObject obj;
        obj.insert("Accept:", "application/json");
       // obj.insert("Accept-Encoding:", "gzip, deflate, br");
        obj.insert("Accept-Language:","zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        obj.insert("Cache-Control:", "no-cache");
        obj.insert("Connection:","keep-alive");
        //obj.insert("Content-Length:","1246");
        obj.insert("Content-Type:", "application/x-www-form-urlencoded");
        //obj.insert("Cookie","pgv_pvid=488475832; fqm_pvqid=e588e3a3-b854-4507-83c4-2e834e990a9f; ts_refer=ADTAGmyqq; ts_uid=1297351523; fqm_sessionid=0a3d488f-c1f8-4e2a-a43b-eaf2966d4924; pgv_info=ssid=s9313757170; qqmusic_key=W_X_3irMC360nSU3_hSdPGiWvtGmhis551yOHkPRXIz4QA1-xIt3IJgqZLVJUnqgI4830PXixgp4Jfy5Z0; qm_keyst=W_X_3irMC360nSU3_hSdPGiWvtGmhis551yOHkPRXIz4QA1-xIt3IJgqZLVJUnqgI4830PXixgp4Jfy5Z0; psrf_qqunionid=; tmeLoginType=1; psrf_qqaccess_token=; psrf_qqrefresh_token=; psrf_qqopenid=; wxuin=1152921504854169144; euin=oK6kowEAoK4z7eck7e6sNK6P7n**; wxunionid=oqFLxsvM2Fq-9zHfGbwo41giiUJ0; wxrefresh_token=46_4mPY4HH5gyS0Li2IrPFOkgoaJipPYhZ14viUF_CMN_x_LRxlhaefMgwxTWzMJC-Qw-f2q6_8fMxNsu-xnNGW876Z6bVlElOl5zxa-Kpl4tw; wxopenid=opCFJw4A9aB2rl3nE1dAfqGJNwbk; wxuin=1152921504854169144; qm_keyst=W_X_3irMC360nSU3_hSdPGiWvtGmhis551yOHkPRXIz4QA1-xIt3IJgqZLVJUnqgI4830PXixgp4Jfy5Z0; login_type=2; ts_last=y.qq.com/n/ryqq/player");
        //obj.insert("Host:", "u.y.qq.com");
        //obj.insert("Origin: ", "https://y.qq.com");
        obj.insert("Referer:", "https://y.qq.com/");
        obj.insert("User-Agent:", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0");
        obj.insert("Pragma:","no-cache");
        obj.insert("data:",QString("%1").arg(ui->lineEdit->text()));
        //obj.insert("Cache-Control:","max-age=0");
        QByteArray byteArray = QJsonDocument(obj).toJson(QJsonDocument::Compact);
        //qDebug() << "user Info" << obj << endl;
        QString str(byteArray);
        qDebug()<<str;
        ui->textBrowser->setPlainText(str);
        if(reply != Q_NULLPTR)
        {
            //更改reply指向位置钱一定要保证之前的定义了自动delete
        reply->deleteLater();
        }
       reply= m_accessManager->post(request,byteArray);
        connect(reply, &QNetworkReply::finished, this, &Widget::finished);

}

//这个函数就可以实现混合数据表单上传了，切记加入filename属性，否则真的很无奈
void Widget::upDatasToCloud()
{
    QString path_face="/home/w642833823/";
    QString path_shetai="/home/w642833823/图片/";
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    /* tokenid */
    QHttpPart textPart;    textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"tokenid\""));
    textPart.setBody("001001");
    multiPart->append(textPart);
    /* mid */
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"mid\""));
    textPart.setBody(this->ui->lineEdit->text().toUtf8());
    multiPart->append(textPart);


    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"pic1\"; filename=\""+path_face+"\""));
    QFile *file = new QFile(path_face);
    file->open(QIODevice::ReadOnly);
    imagePart.setBodyDevice(file);
    //file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
    multiPart->append(imagePart);

    QHttpPart imagePart1;
    imagePart1.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
    imagePart1.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"pic2\"; filename=\""+path_shetai+"\""));
    QFile *file1 = new QFile(path_shetai);
    file1->open(QIODevice::ReadOnly);
    imagePart1.setBodyDevice(file1);
    //file1->setParent(multiPart);
    multiPart->append(imagePart1);


    QUrl url("http:your post url");
    QNetworkRequest *request=new QNetworkRequest(url);

    QNetworkAccessManager *manager =new QNetworkAccessManager();
    QNetworkReply *reply = manager->post(*request, multiPart);
    multiPart->setParent(reply); // delete the multiPart with the reply
                                 // here connect signals etc.

//更新上传进度
    QObject::connect(reply, &QNetworkReply::uploadProgress, [this](int a, int b) {

        this->ui->textBrowser->setText(QString::number(((float)a) / b));
    });
    QObject::connect(reply, &QNetworkReply::readyRead, [=]() {
        qDebug() << "rpy:"<< reply->errorString() << reply->readAll();
        //文件关闭很多种，但是切记不能提前关闭，否则上传进度卡死。
        file->close();
        file1->close();
    });
}

void Widget::on_pushButton_2_clicked()
{
   this-> upDatasToCloud();

}
